package com.weilive.core.common;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SharedTimer {
	private SharedTimer() {
	}

	// 默认1个
	private static ScheduledThreadPoolExecutor schedule = null;

	public static final void init(int poolSize) {
		if (schedule == null) {
			schedule = new ScheduledThreadPoolExecutor(poolSize);
		}
	}

	private static ScheduledThreadPoolExecutor getSchedule() {
		if (schedule == null) {
			schedule = new ScheduledThreadPoolExecutor(1);
		}
		return schedule;
	}

	/**
	 * 指定一个任务在多少时间后执行,执行一次
	 * 
	 * @param task
	 * @param delay
	 */
	public static synchronized void schedule(Runnable task, long delay) {
		if (delay < 0) {
			delay = 0;
		}
		getSchedule().schedule(task, delay, TimeUnit.MILLISECONDS);
	}

	/**
	 * 指定一个任务在多少时间后执行,重复执行
	 * 
	 * @param task
	 * @param delay
	 * @param period
	 */
	public static void schedule(Runnable task, long delay, long period) {
		if (delay < 0) {
			delay = 0;
		}
		if (period > 0) {
			getSchedule().scheduleWithFixedDelay(task, delay, period, TimeUnit.MILLISECONDS);
		} else {
			getSchedule().schedule(task, delay, TimeUnit.MILLISECONDS);
		}
	}
}
